<template>
    <div class="fuel-expenses-page">
        <div class="page-title">油费管理</div>

        <!-- 搜索区域 -->
        <div class="search-bar card">
            <div class="form-row">
                <label class="form-label">车牌号:</label>
                <input v-model.trim="query.plateNumber" class="input" placeholder="请输入车牌号" />

                <label class="form-label">经办人:</label>
                <input v-model.trim="query.agent" class="input" placeholder="请输入经办人" />

                <label class="form-label">支付方式:</label>
                <select v-model="query.payMethod" class="select">
                    <option value="">全部</option>
                    <option value="微信支付">微信支付</option>
                    <option value="支付宝支付">支付宝支付</option>
                    <option value="现金支付">现金支付</option>
                    <option value="银行转账">银行转账</option>
                </select>

                <button class="btn primary" @click="handleSearch">查询</button>
                <button class="btn" @click="handleReset">重置</button>
            </div>
        </div>

        <!-- 操作按钮 -->
        <div class="toolbar">
            <button class="btn primary" @click="handleCreate">新增</button>
            <button class="btn danger" :disabled="selectedRowIds.length === 0" @click="handleBatchDelete">删除</button>
        </div>

        <!-- 数据表格 -->
        <div class="card">
            <table class="table">
                <thead>
                    <tr>
                        <th class="col-checkbox">
                            <input type="checkbox" :checked="isAllChecked" @change="toggleAll($event)" />
                        </th>
                        <th>车牌号</th>
                        <th>加油费用/元</th>
                        <th>加油量/L</th>
                        <th>起始公里数</th>
                        <th>支付方式</th>
                        <th>经办人</th>
                        <th>备注</th>
                        <th>创建时间</th>
                        <th class="col-actions">操作</th>
                    </tr>
                </thead>
                <tbody>
                    <tr v-for="row in pagedList" :key="row.id">
                        <td class="col-checkbox">
                            <input type="checkbox" :checked="selectedRowIds.includes(row.id)"
                                @change="toggleOne(row.id, $event)" />
                        </td>
                        <td>{{ row.plateNumber }}</td>
                        <td>{{ row.cost }}</td>
                        <td>{{ row.volume }}</td>
                        <td>{{ row.startMileage }}</td>
                        <td>{{ row.payMethod }}</td>
                        <td>{{ row.agent }}</td>
                        <td>{{ row.remark || '-' }}</td>
                        <td>{{ row.createTime }}</td>
                        <td class="col-actions">
                            <a href="javascript:void(0)" @click="handleEdit(row)">编辑</a>
                            <span class="divider">|</span>
                            <a href="javascript:void(0)" class="danger" @click="handleDelete(row)">删除</a>
                            <span class="divider">|</span>
                            <a href="javascript:void(0)" @click="handleView(row)">查看</a>
                        </td>
                    </tr>
                    <tr v-if="pagedList.length === 0">
                        <td class="empty" colspan="10">暂无数据</td>
                    </tr>
                </tbody>
            </table>

            <!-- 分页 -->
            <div class="pagination">
                <div class="summary">共{{ totalPages }}页/{{ totalCount }}条数据</div>

                <div class="pager">
                    <button class="pager-btn" :disabled="page === 1" @click="goTo(page - 1)">‹</button>
                    <button v-for="p in pagesToShow" :key="p" class="pager-btn" :class="{ active: page === p }"
                        @click="goTo(p)">{{ p }}</button>
                    <button class="pager-btn" :disabled="page === totalPages || totalPages === 0"
                        @click="goTo(page + 1)">›</button>

                    <span class="goto">
                        跳至
                        <input class="goto-input" type="number" v-model.number="gotoPage" min="1"
                            :max="Math.max(totalPages, 1)" />
                        页
                        <button class="pager-btn" @click="confirmGoto">确定</button>
                    </span>
                </div>
            </div>
        </div>
    </div>

    <!-- 详情弹窗 -->
    <div v-if="showDetail" class="modal-mask">
        <div class="modal">
            <div class="modal-header">
                <div>油费详情</div>
                <button class="modal-close" @click="closeDetail">×</button>
            </div>
            <div class="modal-body">
                <div v-if="detailLoading">加载中...</div>
                <div v-else-if="!detail">无数据</div>
                <div v-else>
                    <div class="detail-row"><span class="label">车牌号：</span><span>{{ detail.plateNumber || '-' }}</span>
                    </div>
                    <div class="detail-row"><span class="label">加油费用：</span><span>{{ detail.cost }}</span></div>
                    <div class="detail-row"><span class="label">加油量：</span><span>{{ detail.volume }}</span></div>
                    <div class="detail-row"><span class="label">起始公里数：</span><span>{{ detail.startMileage }}</span>
                    </div>
                    <div class="detail-row"><span class="label">支付方式：</span><span>{{ detail.payMethod }}</span></div>
                    <div class="detail-row"><span class="label">经办人：</span><span>{{ detail.agent }}</span></div>
                    <div class="detail-row"><span class="label">备注：</span><span>{{ detail.remark || '-' }}</span></div>
                    <div class="detail-row"><span class="label">创建时间：</span><span>{{ detail.createTime }}</span></div>
                </div>
            </div>
            <div class="modal-footer">
                <button class="btn primary" @click="closeDetail">确定</button>
            </div>
        </div>
    </div>

</template>

<script setup lang="ts">
import { computed, onMounted, reactive, ref, watch } from 'vue'
import { read, write } from '@/assets/Axios/axiosHttple'

type FuelExpense = {
    id: number
    plateNumber: string
    cost: number
    volume: number
    startMileage: number
    payMethod: string
    agent: string
    remark?: string
    createTime: string
}

// 查询条件
const query = reactive({
    plateNumber: '',
    agent: '',
    payMethod: ''
})

// 表格数据（服务端获取）
const allList = ref<FuelExpense[]>([])
const totalCount = ref(0)
const loading = ref(false)

// 选择
const selectedRowIds = ref<number[]>([])
const isAllChecked = computed(() =>
    pagedList.value.length > 0 && pagedList.value.every(r => selectedRowIds.value.includes(r.id))
)

// 分页
const page = ref(1)
const pageSize = ref(10)
const gotoPage = ref<number | ''>('')

const totalPages = computed(() => Math.ceil(totalCount.value / pageSize.value))
const pagedList = computed(() => allList.value)

const pagesToShow = computed(() => {
    const total = totalPages.value
    if (total === 0) return [] as number[]
    const max = 7
    const result: number[] = []
    let start = Math.max(1, page.value - 3)
    let end = Math.min(total, start + max - 1)
    if (end - start + 1 < max) start = Math.max(1, end - max + 1)
    for (let i = start; i <= end; i++) result.push(i)
    return result
})

function goTo(p: number) {
    if (p < 1 || p > totalPages.value) return
    page.value = p
    fetchList()
}

function confirmGoto() {
    if (typeof gotoPage.value === 'number') {
        goTo(gotoPage.value)
    }
}

function handleSearch() {
    page.value = 1
    fetchList()
}

function handleReset() {
    query.plateNumber = ''
    query.agent = ''
    query.payMethod = ''
    page.value = 1
    fetchList()
}

function toggleAll(ev: Event) {
    const checked = (ev.target as HTMLInputElement).checked
    if (checked) {
        const ids = pagedList.value.map(r => r.id)
        // 合并去重
        selectedRowIds.value = Array.from(new Set([...selectedRowIds.value, ...ids]))
    } else {
        const ids = new Set(pagedList.value.map(r => r.id))
        selectedRowIds.value = selectedRowIds.value.filter(id => !ids.has(id))
    }
}

function toggleOne(id: number, ev: Event) {
    const checked = (ev.target as HTMLInputElement).checked
    if (checked) {
        if (!selectedRowIds.value.includes(id)) selectedRowIds.value.push(id)
    } else {
        selectedRowIds.value = selectedRowIds.value.filter(x => x !== id)
    }
}

function handleCreate() {
    window.location.href = '/AddFuelExpenses'
}

function handleEdit(row: FuelExpense) {
    window.location.href = `/UpdateFuelExpenses?id=${encodeURIComponent(String(row.id))}`
}

function handleDelete(row: FuelExpense) {
    if (!confirm('确认删除该记录吗？')) return
    write.post('baseinfowrite/api/FuelExpenses/Delete', { id: row.id, deletedBy: localStorage.getItem('username') || 'system' })
        .then(({ data, status }) => {
            if (status === 200 && (data?.code === 200 || data?.data === true)) {
                fetchList()
            } else {
                console.error('删除失败', data)
            }
        })
        .catch(err => { console.error('删除接口异常', err) })
}

function handleBatchDelete() {
    if (selectedRowIds.value.length === 0) return
    if (!confirm(`确认删除选中的 ${selectedRowIds.value.length} 条记录吗？`)) return
    const payload = {
        ids: selectedRowIds.value,
        deletedBy: localStorage.getItem('username') || 'system'
    }
    write.post('baseinfowrite/api/FuelExpenses/BatchDelete', payload)
        .then(({ data, status }) => {
            if (status === 200 && (data?.code === 200)) {
                selectedRowIds.value = []
                fetchList()
            } else {
                console.error('批量删除失败', data)
            }
        })
        .catch(err => { console.error('批量删除接口异常', err) })
}

function handleView(row: FuelExpense) {
    openDetail(row.id)
}

type FuelListResponse = { totalCount: number; totalPage: number; data: any[] }

// 获取列表（服务端分页）
async function fetchList() {
    loading.value = true
    try {
        const normalizeMethod = (v: any) => {
            const s = String(v ?? '').trim()
            if (!s) return ''
            if (s === '现金' || s === '现金支付') return '线下支付'
            if (s === '银行转账') return '企业转账'
            return s
        }
        const stdMethod = normalizeMethod(query.payMethod)
        const params = {
            PageIndex: page.value,
            PageSize: pageSize.value,
            licensePlateNumber: query.plateNumber || undefined,
            handler: query.agent || undefined,
            paymentMethod: stdMethod || undefined,
            PaymentMethod: stdMethod || undefined,
            payMethod: stdMethod || undefined
        }
        const res = await read.get('baseinforead/api/FuelExpenses/GetFuelExpensesList', { params })
        const data = res?.data
        if (res?.status === 200 && data?.code === 200) {
            const items = Array.isArray(data?.data?.data) ? data.data!.data : []
            // 若后端未按支付方式过滤，则在前端做一次兜底过滤
            const filtered = stdMethod
                ? items.filter((it: any) => normalizeMethod(it.paymentMethod ?? it.payMethod ?? it.pay_type ?? it.payType) === stdMethod)
                : items
            const list = filtered.map((it: any, idx: number) => {
                const id = it.id ?? it.fuelExpenseId ?? (idx + 1) + (page.value - 1) * pageSize.value
                const row: FuelExpense = {
                    id,
                    plateNumber: it.licensePlateNumber ?? it.plateNumber ?? '-',
                    cost: it.fuelCost ?? it.cost ?? 0,
                    volume: it.fuelQuantity ?? it.volume ?? 0,
                    startMileage: it.startMileage ?? 0,
                    payMethod: normalizeMethod(it.paymentMethod ?? it.payMethod ?? it.pay_type ?? it.payType) || '-',
                    agent: it.handler ?? '-',
                    remark: it.remarks ?? it.remark ?? '-',
                    createTime: it.createdAt ?? it.createTime ?? ''
                }
                return row
            })
            allList.value = list
            totalCount.value = (data?.data && typeof data.data.totalCount === 'number' && !stdMethod)
                ? data.data.totalCount
                : list.length
        } else {
            allList.value = []
            totalCount.value = 0
        }
    } catch (e) {
        allList.value = []
        totalCount.value = 0
        console.error(e)
    } finally {
        loading.value = false
    }
}

// 详情
const showDetail = ref(false)
const detailLoading = ref(false)
const detail = ref<any>(null)

function closeDetail() { showDetail.value = false }

async function openDetail(id: number) {
    showDetail.value = true
    detailLoading.value = true
    detail.value = null
    try {
        const r1 = await read.get(`baseinforead/api/FuelExpenses/GetFuelExpensesById/${encodeURIComponent(String(id))}`)
        const d = r1?.data?.data || null
        if (!d) { detail.value = null; return }
        detail.value = {
            id: d.id ?? id,
            plateNumber: d.licensePlateNumber ?? d.plateNumber ?? '-',
            cost: d.fuelCost ?? d.cost ?? 0,
            volume: d.fuelQuantity ?? d.volume ?? 0,
            startMileage: d.startMileage ?? 0,
            payMethod: d.paymentMethod ?? '-',
            agent: d.handler ?? '-',
            remark: d.remarks ?? d.remark ?? '-',
            createTime: d.createdAt ?? d.createTime ?? ''
        }
    } catch (e) {
        console.error('获取油费详情失败', e)
        detail.value = null
    } finally {
        detailLoading.value = false
    }
}

onMounted(fetchList)
watch(pageSize, () => {
    page.value = 1
    fetchList()
})

// 新增/编辑成功后刷新回显（使用 refresh=1 约定）
if (new URLSearchParams(location.search).get('refresh') === '1') {
    handleSearch()
    const url = new URL(location.href)
    url.searchParams.delete('refresh')
    history.replaceState(null, '', url.toString())
}
</script>

<style scoped>
.fuel-expenses-page {
    padding: 16px 20px;
    color: #333;
    font-size: 14px;
}

.page-title {
    font-size: 18px;
    margin-bottom: 12px;
}

.card {
    background: #fff;
    border: 1px solid #e5e6eb;
    border-radius: 4px;
}

.search-bar {
    padding: 16px;
    margin-bottom: 12px;
}

.form-row {
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    gap: 8px 12px;
}

.form-label {
    color: #666;
}

.input,
.select {
    height: 32px;
    line-height: 32px;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    padding: 0 10px;
    min-width: 180px;
}

.btn {
    height: 32px;
    padding: 0 14px;
    border: 1px solid #dcdfe6;
    background: #fff;
    border-radius: 4px;
    cursor: pointer;
}

.btn:disabled {
    opacity: 0.6;
    cursor: not-allowed;
}

.btn.primary {
    background: #409eff;
    border-color: #409eff;
    color: #fff;
}

.btn.danger {
    color: #f56c6c;
    border-color: #f56c6c;
}

.toolbar {
    margin: 8px 0 12px 0;
    display: flex;
    gap: 8px;
}

.table {
    width: 100%;
    border-collapse: collapse;
}

.table thead th {
    text-align: left;
    background: #f7f8fa;
    border-bottom: 1px solid #e5e6eb;
    padding: 10px 12px;
    color: #666;
    font-weight: 400;
}

.table tbody td {
    border-bottom: 1px solid #f0f0f0;
    padding: 10px 12px;
}

.col-checkbox {
    width: 36px;
}

.col-actions {
    width: 168px;
    white-space: nowrap;
}

.divider {
    color: #d0d0d0;
    margin: 0 6px;
}

.danger {
    color: #f56c6c;
}

.empty {
    text-align: center;
    color: #909399;
}

.pagination {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 12px;
}

.summary {
    color: #909399;
}

.pager {
    display: flex;
    align-items: center;
    gap: 4px;
}

.pager-btn {
    min-width: 28px;
    height: 28px;
    padding: 0 8px;
    border: 1px solid #dcdfe6;
    background: #fff;
    border-radius: 3px;
    cursor: pointer;
}

.pager-btn.active {
    background: #409eff;
    border-color: #409eff;
    color: #fff;
}

.goto {
    margin-left: 8px;
    color: #606266;
}

.goto-input {
    width: 56px;
    height: 28px;
    margin: 0 6px;
    padding: 0 6px;
    border: 1px solid #dcdfe6;
    border-radius: 3px;
}

/* 详情弹窗样式 */
.modal-mask {
    position: fixed;
    inset: 0;
    background: rgba(0, 0, 0, .35);
    display: flex;
    align-items: center;
    justify-content: center;
}

.modal {
    width: 520px;
    background: #fff;
    border-radius: 6px;
    overflow: hidden;
    border: 1px solid #e5e6eb;
}

.modal-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 10px 12px;
    border-bottom: 1px solid #eee;
}

.modal-close {
    background: none;
    border: none;
    font-size: 18px;
    cursor: pointer;
}

.modal-body {
    padding: 12px 16px;
    max-height: 60vh;
    overflow: auto;
}

.modal-footer {
    padding: 10px 12px;
    text-align: right;
    border-top: 1px solid #eee;
}

.detail-row {
    display: flex;
    gap: 8px;
    padding: 6px 0;
}

.detail-row .label {
    width: 100px;
    color: #666;
}
</style>
